package com.xjtu.weixin.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.xjtu.weixin.builder.TextBuilder;
import com.xjtu.weixin.mapper.MpAutoResponseMapper;
import com.xjtu.weixin.mapper.MpTextTemplateMapper;
import com.xjtu.weixin.model.entity.MpAutoResponse;
import com.xjtu.weixin.model.entity.MpTextTemplate;
import com.xjtu.weixin.service.MpAutoResponseService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * ${DESCRIPTION}
 *
 * @author 杨凯
 * @create 2018-09-04 10:18
 **/
@Service
@Slf4j
public class MpAutoResponseServiceImpl implements MpAutoResponseService {

	@Autowired
	private MpAutoResponseMapper autoResponseMapper;

	@Autowired
	private MpTextTemplateMapper templateMapper;


	@Override
	public List<MpAutoResponse> getKeywordsList() {
		return autoResponseMapper.selectList(new EntityWrapper<>());
	}

	@Override
	public void addKeywords(MpAutoResponse mpAutoResponse) {
		autoResponseMapper.insert(mpAutoResponse);
	}

	@Override
	public WxMpXmlOutMessage getAutoResponseMsg(WxMpXmlMessage wxMessage, WxMpService service) {

		final List<MpAutoResponse> autoResponseList = autoResponseMapper.selectList(new EntityWrapper<>());

		//判断是否为文本消息
		if (wxMessage.getMsgType().equals(WxConsts.XmlMsgType.TEXT)) {
			if (!autoResponseList.isEmpty()) {
				//循环匹配关键字
				for(MpAutoResponse response : autoResponseList){
					if(wxMessage.getContent().equals(response.getKeyword())){
						final MpTextTemplate textTemplate = templateMapper.selectById(response.getTemplateId());
						return new TextBuilder().build(textTemplate.getTemplateContent(),wxMessage,service);
					}
				}
			}else{
				//TODO 不识别关键字
			}

		}
		return null;
	}
}
